package com.moniteach.server.servlet;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;

import com.moniteach.server.db.bo.Group;
import com.moniteach.server.db.bo.Message;
import com.moniteach.server.db.bo.UserGroup;
import com.moniteach.server.db.bo.UserInfo;
import com.moniteach.server.db.connector.PMF;
import com.moniteach.utils.Resource;

public class UserGroupServlet extends CommonServlet {
	private String action;
	private String id;
	private String group;
	private String user;
	private String visibility;

	@Override
	protected void prepare(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("UTF-8");

		action = req.getParameter(Resource.Const.action);
		if ("".equals(action) || action == null) {
			resp.getWriter().print(Resource.Const.no + "ACTION");
			return;
		}

		id = req.getParameter(Resource.Const.id);
		group = req.getParameter(Resource.Const.group);
		user = req.getParameter(Resource.Const.user);
		visibility = req.getParameter(Resource.Const.visibility);

		String response = "";
		if (Resource.Action.CREATE.equals(action)) {
			response = create();
		} else if (Resource.Action.GET_BY_ID.equals(action)) {
			response = getById();
		} else if (Resource.Action.GET_ALL_GROUP_USER.equals(action)) {
			response = getAllGroupUser();
		} else if (Resource.Action.GET_ALL_USER_GROUP.equals(action)) {
			response = getAllUserGroup();
		} else if (Resource.Action.MODIFY.equals(action)) {
			response = modify();
		}
		resp.getWriter().print(response);
	}

	private String getAllGroupUser() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(UserGroup.class);
		try {
			query.setFilter(String.format(
					"user == %1$s && visibility == true", user));
			List<UserGroup> results = (List<UserGroup>) query.execute();

			if (!results.isEmpty()) {
				JSONArray objectsArray = new JSONArray();
				for (UserGroup userGroup : results) {
					PersistenceManager pm1 = PMF.get().getPersistenceManager();
					try {
						Long idLong = Long.valueOf(userGroup.getGroup());
						Group entityGroup = pm.getObjectById(Group.class,
								idLong);
						objectsArray.put(entityGroup.toJSONObject());
					} catch (Exception e) {
						return Resource.Const.no;
					} finally {
						pm1.close();
					}
				}
				return objectsArray.toString();
			} else {
				return Resource.Const.no;
			}
		} catch (Exception e) {
			return Resource.Const.no;
		} finally {
			pm.close();
		}
	}
	
	private String getAllUserGroup() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(UserGroup.class);
		try {
			query.setFilter(String.format(
					"group == %1$s && visibility == true", group));
			List<UserGroup> results = (List<UserGroup>) query.execute();

			if (!results.isEmpty()) {
				JSONArray objectsArray = new JSONArray();
				for (UserGroup userGroup : results) {
					PersistenceManager pm1 = PMF.get().getPersistenceManager();
					try {
						Long idLong = Long.valueOf(userGroup.getUser());
						UserInfo entityUser= pm.getObjectById(UserInfo.class,
								idLong);
						objectsArray.put(entityUser.toJSONObject());
					} catch (Exception e) {
						return Resource.Const.no;
					} finally {
						pm1.close();
					}
				}
				return objectsArray.toString();
			} else {
				return Resource.Const.no;
			}
		} catch (Exception e) {
			return Resource.Const.no;
		} finally {
			pm.close();
		}
	}

	@Override
	protected String create() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Long groupLong = Long.valueOf(group);
			Group entityGroup = pm.getObjectById(Group.class, groupLong);

			Long userLong = Long.valueOf(user);
			UserInfo entityUser = pm.getObjectById(UserInfo.class, userLong);

			Boolean visibilityBoolean = Boolean.valueOf(visibility);

			UserGroup oneUserGroup = new UserGroup(entityUser.getId(),
					entityGroup.getId(), visibilityBoolean);
			pm.makePersistent(oneUserGroup);
			return String.valueOf(oneUserGroup.getId());
		} catch (Exception e) {
			return Resource.Const.no;
		} finally {
			pm.close();
		}
	}

	@Override
	protected String get() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected String getById() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Long idLong = Long.valueOf(id);
			UserGroup entityUserGroup = pm.getObjectById(UserGroup.class,
					idLong);
			return entityUserGroup.toJSONObject().toString();
		} catch (Exception e) {
			return Resource.Const.no;
		} finally {
			pm.close();
		}
	}

	@Override
	protected String getAll() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected String modify() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Long idLong = Long.valueOf(id);
			UserGroup entityUserGroup = pm.getObjectById(UserGroup.class,
					idLong);

			if (visibility != null) {
				Boolean visibilityBoolean = Boolean.valueOf(visibility);
				entityUserGroup.setVisibility(visibilityBoolean);
			}
			pm.makePersistent(entityUserGroup);
			return Resource.Const.ok;
		} catch (Exception e) {
			return Resource.Const.no;
		} finally {
			pm.close();
		}
	}
}
